package com.atguigu.chapter05.transform;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/7/16 15:15
 */
public class Flink07_Agg {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        // select id, sum(vc), 'abc' from .. group by id
        DataStreamSource<WaterSensor> s1 = env.fromElements(
            new WaterSensor("sensor_1", 1L, 10),
            new WaterSensor("sensor_1", 4L, 40),
            new WaterSensor("sensor_2", 3L, 30),
            new WaterSensor("sensor_1", 2L, 40),
            new WaterSensor("sensor_1", 5L, 50)
        );
        
        // 分别计算每个传感器的水位和!
        s1
            .keyBy(new KeySelector<WaterSensor, String>() {
                @Override
                public String getKey(WaterSensor value) throws Exception {
                    return value.getId();
                }
            })
           // .sum("vc")
//            .max("vc")
            //.min("vc")
//            .maxBy("vc")  //
            .maxBy("vc", false)  //
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
/*
聚合算子:
    必须在keyBy之后使用


sum, max, min
    非聚合和分组字段默认选的是碰到的第一个值
    
 maxBy, minBy
     非聚合和分组字段 是最终最大值或最小值
     默认情况: 如果最大值相等, 其他字段取第一个
 
 
 */